var map;
var current_position; // Variable
var current_position_marker; // Object
var current_search_marker; // Object

var markers = [];
var geolocationEnabled = true;
var fifaSchedule;

// Constants
var Constants = {
        // URL_BASE: 'http://190.30.171.57/',
        URL_BASE: 'http://192.168.1.82/', 
        DIETARY_CHECKBOX: "DietaryCheckbox",
        ORGANIC_GARDENS_CHECKBOX: "OrganicGardensCheckbox",
        SUPERMARKETS_CHECKBOX: "SupermarketsCheckbox",

        CELIAC_SERVICES_CHECKBOX: "CeliacServicesCheckbox",
        CELIAC_PRODUCTS_CHECKBOX: "CeliacProductsCheckbox",
        CELIAC_RESTAURANTS_CHECKBOX: "CeliacRestaurantsCheckbox",
        RESTAURANT_GF_MENU_CHECKBOX: "RestaurantGlutenFreeMenuCheckbox",
        VEGETARIAN_RESTAURANT_CHECKBOX: "VegetarianRestaurantsCheckbox",
        
        ENGLISH_CHECKBOX: "EnglishCheckbox",
        SPANISH_CHECKBOX: "SpanishCheckbox",
        
        CURRENT_LANGUAGE: "CurrentLanguage",
        
        WON_POINTS: 3,
        DRAW_POINTS: 1
};

var StadiumsImg = {
	'AMAZONIA':           'arena_amazonia.jpg',
	'BAIXADA':            'arena_da_baixada.jpg',
	'SAO_PAULO':          'arena_de_sao_paulo.jpg',
	'FONTE':              'arena_fonte_nova.jpg',
	'PANTANAL':           'arena_pantanal.jpg',
	'PERNAMBUCO':         'arena_pernambuco.jpg',
	'BEIRA':              'beira_rio.jpg',
	'CASTELAO':           'castelao.jpg',
	'DUNAS':              'das_dunas.jpg',
	'MARACANA':           'maracana.jpg',
	'MINEIRAO':           'mineirao.jpg',
	'NACIONAL':           'nacional.jpg'
};

var CssTeamFlags = {
	'BRAZIL':             'flagsp_bra',
	'CROATIA':            'flagsp_cro',
	'MEXICO':             'flagsp_mex',
	'CAMEROON':           'flagsp_cmr',
	'SPAIN':              'flagsp_esp',
	'NETHERLANDS':        'flagsp_ned',
	'CHILE':              'flagsp_chi',
	'AUSTRALIA':          'flagsp_aus',
	'COLOMBIA':           'flagsp_col',
	'GREECE':             'flagsp_gre',
	'COSTA_DE_MARFIL':    'flagsp_civ',
	'JAPAN':              'flagsp_jpn',
	'URUGUAY':            'flagsp_uru',
	'COSTA_RICA':         'flagsp_crc',
	'ENGLAND':            'flagsp_eng',
	'ITALY':              'flagsp_ita',
	'SWITZERLAND':        'flagsp_sui',
	'ECUADOR':            'flagsp_ecu',
	'FRANCE':             'flagsp_fra',
	'HONDURAS':           'flagsp_hon',
	'ARGENTINA':          'flagsp_arg',
	'BOSNIA':             'flagsp_bih',
	'IRAN':               'flagsp_irn',
	'NIGERIA':            'flagsp_nga',
	'GERMANY':            'flagsp_ger',
	'PORTUGAL':           'flagsp_por',
	'GHANA':              'flagsp_gha',
	'USA':                'flagsp_usa',
	'BELGIUM':            'flagsp_bel',
	'ALGERIA':            'flagsp_alg',
	'RUSSIA':             'flagsp_rus',
	'KOREA':              'flagsp_kor'
	
};

var app = {

    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
     bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
  			                             
        checkConnection();                               
 		
 		facebookInitialize();
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        console.log('Received Event: ' + id);
    }
    
    
};


function checkConnection() {
    
    console.log("Function checkConnection()");  
        initGmap();
                               
/*    if(navigator.connection.type == Connection.NONE){
        
        $( "#popup_network_connection" ).popup();
        $( "#popup_network_connection" ).popup("open");
    }
    else
    {
        console.log("initGmap()");  
        
    }*/
}


// Pablo
function facebookInitialize() {

	console.log("Function facebookInitialize()");
	
	try {
			// alert('Device is ready! Make sure you set your app_id below this alert.');

   			FB.init({ appId: "475733615864423", nativeInterface: CDV.FB, useCachedDialogs: false });
   
        
		} catch (e) {
         alert(e);
	}
          
}

// Pablo
function postToWall(){
	
	console.log("Function postToWall()");
	
	var params = {
		method: 'feed',
		name: 'Facebook Dialogs',
		link: 'https://developers.facebook.com/docs/reference/dialogs/',
		picture: 'http://fbrell.com/f8.jpg',
		caption: 'Reference Documentation',
		from:"266065413547125",
		to:"266065413547125",
		description: '@Fifa-Mobile-For-Health-Community'
	};
	
	console.log(params);
	FB.ui(params, function(obj) { console.log(obj);});
}

// GMAPS Code
function initGmap(){

    console.log("Function initGmap()");

    // Configuration from local Storage
    initConfiguration();  
       
    if(navigator.geolocation) {
        
        // Get current position    
        navigator.geolocation.getCurrentPosition(geolocationSuccess, getDefaultPosition);
    }
    else {
        geolocationEnabled = false;
        alert("Your browser does not support geolocation");  
    }
    
    // Init address search
    initAddressSearch();
      
    $("#refresh_position").click(function() {
    
        navigator.geolocation.getCurrentPosition(geolocationSuccess, getDefaultPosition);
   
    });
    
    // Load the spinner if an ajaxStart occurs; stop when it is finished
    $(document).on({
      ajaxStart: function() { 
        $.mobile.loading('show', 
                        { 
                            theme:'a' 
                        });
      },
      ajaxStop: function() {
        $.mobile.loading('hide');
      }    
    });

}

// Input Address search behavior
function initAddressSearch() {

    console.log("Function initAddressSearch()");
    
    $('#address_search_button').val(translate('SEARCH'));

    $("#address_search_button").focus(function(event, ui) {
  
        $("#address_search_button").val("");
    });

    $("#address_search_button").focusout(function(event, ui) {
  
        if ($("#address_search_button").val() == "")
        {
            $("#address_search_button").val(translate('SEARCH'));
            
            current_search_marker.setMap(null);       
            current_search_marker = null;
        }
    });

    $("#address_search_button").bind( "change", function(event, ui) {
              
        GMaps.geocode({
            address: $('#address_search_button').val(),
            callback: function(results, status) {
                if (status == 'OK') {
                    var latlng = results[0].geometry.location;
                    map.setCenter(latlng.lat(), latlng.lng());
                  
                    setSearchMarker(latlng.lat(), latlng.lng());
                }
            }
        });
    });
}

function setSearchMarker(latitude, longitude) {

    console.log("Function setSearchMarker()");

    if (current_search_marker != null)
    {
        current_search_marker.setPosition(
            new google.maps.LatLng(
                latitude,
                longitude)
        );
    }
    else
    {
        current_search_marker = map.addMarker({
            lat: latitude,
            lng: longitude
        });
    }
}

function getDefaultPosition() {

    console.log("Function getDefaultPosition()");
    current_position = (
    			{ coords:
	                {
	                    latitude: -34.603723,
	                    longitude: -58.381593
	                }
				});

    // Buenos Aires
    //current_position.coords.latitude = -34.603723;
    //current_position.coords.longitude = -58.381593;
    
    geolocationEnabled = false;
    
    showPosition();
}

function geolocationSuccess(position) {
    console.log("Function geolocationSuccess()");
    
    current_position = position;
    showPosition();
}

// Show position at map
function showPosition(){

    console.log("Function showPosition()");

    latitude = current_position.coords.latitude;
    longitude = current_position.coords.longitude;
        
    if (map != null)
    {
        map.setCenter(latitude, longitude);

        current_position_marker.setPosition(
            new google.maps.LatLng(
                latitude,
                longitude)
        );

        if (current_search_marker != null)
        {
            current_search_marker.setMap(null);       
            current_search_marker = null;
        }
    }
    else
    {
        var footer_top = $("#home_footer").position().top;
	    var map_top = $("#map").position().top;
	    var row_top = $("#map_row").position().top;
	    var newheight = footer_top - map_top - 2* (map_top - row_top);
        var sizes = getWindowSizes();
        var height = sizes[1];

        
        $("#map").css("height", newheight + "px");

        console.log("Resizing map to: " + newheight);
     
        //Start gmapsCode
        map = new GMaps({
          div: '#map',
          lat: latitude,
          lng: longitude
/*          click: function(event) {
                var lat = event.latLng.lat();
                var lng = event.latLng.lng();
                
                setSearchMarker(lat, lng);
            } */
        });
    
       // map.addLayer('places');
        
        var image = "css/images/dot20.gif";
        
        current_position_marker = map.addMarker({
          lat: latitude,
          lng: longitude,
          icon: image
        });
        
    }
    
    //GMaps.on('click', map.map, f);
}

function searchNearby() {
    console.log("Function searchNearby()");
      
    var url = Constants.URL_BASE + 'WCFServices/MobileService.svc/json/GetNearbyPlaces';
    var latitude =  current_position.coords.latitude;
    var longitude = current_position.coords.longitude; 
    
    if (current_search_marker != null)
    {
    	console.log("Search marker not null");
        var position = current_search_marker.getPosition();
        
        var latitude =  position.lat();
        var longitude = position.lng();   
    }
    
    var parameters = { latitude: latitude, longitude: longitude };
    
	$.ajaxSetup({ cache: false });
	
    var xhr = $.getJSON(url, parameters);
    xhr.done(loadNearbyResults);
	
	$.ajaxSetup({ cache: true });  
}


function loadNearbyResults(data) {
    
    console.log("Function loadNearbyResults()");
    
    var items, markers_data = [];
    var icon = 'icon_restaurant.png';
 
    if (data != null)
    {
        for (var i = 0; i < data.length; i++) {
             var item = data[i];
             
             switch(item.PlaceTypeID)
             {                   
                case 'VEGETARIAN_RESTAURANT':
					
					if (getPreference(Constants.VEGETARIAN_RESTAURANTS_CHECKBOX) == "false")
                    {
                        continue;
                    }
                    icon = 'icon_vegetarian_restaurant.png';
                    break;
                    
				case 'CELIAC_RESTAURANT':
					
					if (getPreference(Constants.CELIAC_RESTAURANTS_CHECKBOX) == "false")
                    {
                        continue;
                    }
                    icon = 'icon_gf_menu_restaurant.png';
                    break;    
                
                case 'RESTAURANT_GF_MENU':
                
                    if (getPreference(Constants.RESTAURANT_GF_MENU_CHECKBOX) == "false")
                    {
                        continue;
                    }
                    icon = 'icon_celiac_restaurant.png';
                    break;
                
                case 'DIETARY':
                    if (getPreference(Constants.DIETARY_CHECKBOX) == "false")
                    {
                        continue;
                    }   
                    icon = 'icon_dietary.png';
                    break;
                
                case 'ORGANIC_GARDEN':
                    if (getPreference(Constants.ORGANIC_GARDENS_CHECKBOX) == "false")
                    {
                        continue;
                    } 
                    icon = 'icon_organic.png';
                    break;
                
                case 'SUPERMARKET':
                    if (getPreference(Constants.SUPERMARKETS_CHECKBOX) == "false")
                    {
                        continue;
                    } 
                    icon = 'icon_market.png';
                    break;

                
                case 'CELIAC_PRODUCTS':
                    if (getPreference(Constants.CELIAC_PRODUCTS_CHECKBOX) == "false")
                    {
                        continue;
                    } 
                    icon = 'icon_celiac_products.png';
                break;
                
                case 'CELIAC_SERVICE':
                   if (getPreference(Constants.CELIAC_SERVICES_CHECKBOX) == "false")
                    {
                        continue;
                    } 
                    icon = 'icon_celiac_services.png';
                break;

                case 'VEGAN_RESTAURANT':
                   if (getPreference(Constants.VEGAN_RESTAURANT_CHECKBOX) == "false")
                    {
                        continue;
                    } 
                    icon = 'icon_celiac_services.png';
                break;

             }
             
            console.log("Function adding marker Name: " + item.Name +" Latitude: " + item.Latitude + " Longitude: " + item.Longitude);
            var index = map.markers.length;
            
            console.log("Adding marker with index " + index);
            
            var template = $('#place_marker_template').text();
            var content = template.replace(/{{index}}/g, index)
                                   .replace(/{{marker_Name}}/g, item.Name)
                                   .replace(/{{marker_Address}}/g, item.Address)
                                   .replace(/{{marker_Comments}}/g, item.Comments)
                                   .replace(/{{marker_Latitude}}/g, item.Latitude)
                                   .replace(/{{marker_Longitude}}/g, item.Longitude);
              
             map.addMarker({
                  lat : item.Latitude,
                  lng : item.Longitude,
                  title : item.Name,
                      infoWindow: {
                        content : content
                      },
                  icon : "css/images/" + icon
            });
 
        }

    }
}

function getFifaSchedule() {
	
    console.log("Function getFifaSchedule()");
      
    var url = Constants.URL_BASE + 'WCFServices/MobileService.svc/json/GetAllSchedules';
    var parameters = {};
    
    $.ajaxSetup({ cache: false });
    
    var xhr = $.getJSON(url, parameters);
    xhr.done(loadFifaSchedule);
      
	$.ajaxSetup({ cache: true });
}


function loadFifaSchedule(data) {
    
    console.log("Function loadFifaSchedule()");
 
 	fifaSchedule = data;
 	
 	var group = $("#fixture_group option:selected").val();
	var stage = $("#fixture_stage option:selected").val();;
	showSchedule(stage, group);
 	showGroupGrid(stage, group);		
}


function drawRoute(toPosition, travelMode)
{
    console.log("Function drawRoute()");
       
    var latitude = current_position.coords.latitude;
    var longitude = current_position.coords.longitude;

    console.log("Route from: " + latitude +", " + longitude);
    console.log("Route to: " + toPosition[0] +", " + toPosition[1]);
    
    if (map != null)
    {
        map.cleanRoute();

        var index = $("#place_marker_div").data("marker-index");
        console.log("Closing marker index: " + index);
        
        var marker = map.markers[index];
        
        if (marker != null && marker.infoWindow){
          marker.infoWindow.close();
        }
        
        // map.hideInfoWindows();
        
        console.log("Drawing map");
            
        map.drawRoute({
          origin: [ latitude, longitude ],
          destination: toPosition,
          travelMode: travelMode,
          strokeColor: '#131540',
          strokeOpacity: 0.6,
          strokeWeight: 6
        });
    }
    
}


function gps_distance(lat1, lon1, lat2, lon2)
{
    // http://www.movable-type.co.uk/scripts/latlong.html
    var R = 6371; // km
    var dLat = (lat2-lat1) * (Math.PI / 180);
    var dLon = (lon2-lon1) * (Math.PI / 180);
    var lat1 = lat1 * (Math.PI / 180);
    var lat2 = lat2 * (Math.PI / 180);

    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var d = R * c;
    
    return d;
}


/*************************************************/
/** CONFIGURATION AND GENERAL FUNCTIONS          */
/*************************************************/

function getPreference(key, myDefault){

    console.log("Function getPreference()");
     
    try{
       
        var val = window.localStorage.getItem(key);

        console.log("Recover key: " + key + " with value: " + val);
        
        if (val==null || val=='') {
        
            setPreference(key, myDefault);
            return myDefault;
        } else {
            
            return val;
        }
    }
    catch(e){
        aler(e);
        return myDefault;
    }     
}

function setPreference(key, data){

    console.log("Function setPreference()");
    console.log("Store value at key: " + key + " with value: " + data);

    window.localStorage.setItem(key, data);
}

function initializeCheckbox(checkboxID, key) {
    
    console.log("Function initializeCheckbox()");

    var check = getPreference(key, "true");
        
    $(checkboxID).prop("checked", check == "true").checkboxradio('refresh');
    $(checkboxID).change(function() {
        
        var checked = $(checkboxID).prop("checked");
        
        setPreference(key, checked);    
    });
    
}

function initializeRadioGroup(radiogroup, key, changeCallback) {
    
    console.log("Function initializeRadioGroup()");

    var currentValue = getPreference(key);                  
    var options = $("input[name='"+ radiogroup +"']");
    
    $.each(options, function (i, item) {
        
        if ($(this).prop("checked"))
        {
            $(this).prop("checked", "");
        }
    });

    var checked_option = $("input[name='"+ radiogroup +"'][value=" + currentValue + "]");        
    checked_option.prop("checked","checked").checkboxradio("refresh");
    
    $("input[name='"+ radiogroup +"']").on("change", function () {
        setPreference(key, this.value);
        
        if (typeof changeCallback === 'function') {
        changeCallback.call();
    }
    });
    
}

function initConfiguration() {

    console.log("Function initConfiguration()");

    var defaultLanguage = navigator.language || navigator.userLanguage;
    var language = getPreference(Constants.CURRENT_LANGUAGE, defaultLanguage.toUpperCase());

    localizeSite(language);
    
    initializeCheckbox("#checkbox-dietary", Constants.DIETARY_CHECKBOX);
    initializeCheckbox("#checkbox-celiac-restaurants", Constants.CELIAC_RESTAURANTS_CHECKBOX);
    
    initializeCheckbox("#checkbox-vegetarian-restaurants", Constants.VEGETARIAN_RESTAURANTS_CHECKBOX);
	initializeCheckbox("#checkbox-gf-menu-restaurants", Constants.RESTAURANT_GF_MENU_CHECKBOX);
                
    initializeCheckbox("#checkbox-organic-gardens", Constants.ORGANIC_GARDENS_CHECKBOX);
    initializeCheckbox("#checkbox-supermarkets", Constants.SUPERMARKETS_CHECKBOX);
    initializeCheckbox("#checkbox-celiac-products", Constants.CELIAC_PRODUCTS_CHECKBOX);
    initializeCheckbox("#checkbox-celiac-services", Constants.CELIAC_SERVICES_CHECKBOX);
                 
    $("#search_places").click(function() {
        
        searchNearby();
        
        $("#places_search_popup").popup("close");
    });
    
        
    // When the user views the settings page
    $('#settings_page').on('pageshow', function () {
        console.log("Page show: #settings_page");
 
        $("#page_setting_spanish").text(htmlDecode("Espa\u00f1ol"));
 		localizeSite(getPreference(Constants.CURRENT_LANGUAGE));
                    
        initializeRadioGroup('radio-language', Constants.CURRENT_LANGUAGE, function() {
             localizeSite(getPreference(Constants.CURRENT_LANGUAGE));
        });
         
    });
    
    // When the user views the settings page
    $('#info_page').on('pageshow', function () {
        console.log("Page show: #info_page");
 
	              
    });
    
    
	// When the user views the fixture page
    $('#fixture_page').on('pageshow', function () {
    	
        console.log("Page show: #fixture_page");

        $("#refresh_fixture").click(function() {
    
        	getFifaSchedule();
   
    	});
    	
//		$("#show_fixture_grid").click(function() {
//    	});
              
		var stage = $("#fixture_stage option:selected").val();
		var group = $("#fixture_group option:selected").val();

		if (stage == null)
		{
			populateStages("1"); 		
	 		populateGroups("1");
	 	}
	 	else
	 	{   		
    		populateStages(stage);
    		populateGroups(stage, group);
	 	}
 	
 		getFifaSchedule();

        $("#fixture_group").change(function() {
    		var group = $("#fixture_group option:selected").val();
    		var stage = $("#fixture_stage option:selected").val();
    		
    		showSchedule(stage, group);
    		showGroupGrid(stage, group);
        }); 
         		  
        $("#fixture_stage").change(function() {
        	
    		var stage = $("#fixture_stage option:selected").val();
   			    		
 			populateGroups(stage);
    		
			var group = $("#fixture_group option:selected").val();

    		showSchedule(stage, group);
    		
    		$("#grid_container").html('');
        }); 
   
    });        
}

function populateStages(stage){
	
	console.log("Function populateStages()");
	    
	$("#fixture_stage").empty();
	$("#fixture_group").empty();
	
	appendOption($("#fixture_stage"), translate("FIRST_STAGE"), "1");
	appendOption($("#fixture_stage"), translate("SECOND_STAGE"), "2");
	
	$("select#fixture_stage").val(stage);
	
	$("#fixture_stage").selectmenu('refresh', true);
}


function populateGroups(stage, groupDefault){
	
    console.log("Function populateGroups()");
    
	$("#fixture_group").empty();
    			
	if (stage == "1")
	{
	
		appendOption($("#fixture_group"), translate("GROUP") + ": A", "A");
 		appendOption($("#fixture_group"), translate("GROUP") + ": B", "B");
 		appendOption($("#fixture_group"), translate("GROUP") + ": C", "C");
 		appendOption($("#fixture_group"), translate("GROUP") + ": D", "D");
  		appendOption($("#fixture_group"), translate("GROUP") + ": E", "E");
 		appendOption($("#fixture_group"), translate("GROUP") + ": F", "F");
  		appendOption($("#fixture_group"), translate("GROUP") + ": G", "G");
 		appendOption($("#fixture_group"), translate("GROUP") + ": H", "H");

		if (groupDefault == null)
		{
			$("select#fixture_group").val("A");
		}
		else
		{
			$("select#fixture_group").val(groupDefault);
		}

 		$("#fixture_group").selectmenu('refresh', true);
	}
	else
	{
		appendOption($("#fixture_group"), translate("MATCH_ROUND"), "ROUND");
 		appendOption($("#fixture_group"), translate("MATCH_QUARTER"), "QUARTER");
 		appendOption($("#fixture_group"), translate("MATCH_SEMI"), "SEMI");
 		appendOption($("#fixture_group"), translate("MATCH_PLAY"), "PLAY");
  		appendOption($("#fixture_group"), translate("MATCH_FINAL"), "FINAL");
  		
  		if (groupDefault == null)
		{
			$("select#fixture_group").val("ROUND");
		}
		else
		{
			$("select#fixture_group").val(groupDefault);
		}
		
		$("#fixture_group").selectmenu('refresh', true);
	}
	
	$("#fixture_group").selectmenu('refresh', true);
}

function showSchedule(stage, group){
	
	console.log("Function showSchedule()");
		
	var container = $("#fixture_container");
	var content = "";
	
	if (fifaSchedule != null)
	{
		console.log("fifaSchedule not null and Stage: " + stage + " Group: " + group);
			
		if (stage == "1")
		{
			content += "<div class=\"line-separator\"></div>";
		}	
			
	    for (var i = 0; i < fifaSchedule.length; i++) {
		    var item = fifaSchedule[i];

			if (item.Group == group && item.Stage == stage)
			{
				var stadiumJs = 'openStadiumPopup(' + item.StadiumID + ')';		     
				var template = $('#fixture_template').text();
			    content = content + template.replace(/{{LOCAL_TEAM}}/g, translate(item.LocalTeam))
				                            .replace(/{{MATCH_RESULT}}/g, item.LocalGoals + " - " + item.VisitorGoals)
				                            .replace(/{{VISITOR_TEAM}}/g, translate(item.VisitorTeam))
				                            .replace(/{{MATCH_DATE}}/g, item.MatchDate + "  "+ item.MatchTime)
				                            .replace(/{{STADIUM}}/g, item.StadiumName + " - " + item.StadiumCity)
				                            .replace(/{{LOCAL_FLAG}}/g, CssTeamFlags[item.LocalTeam])
				                            .replace(/{{VISITOR_FLAG}}/g, CssTeamFlags[item.VisitorTeam])
				                            .replace(/{{STADIUM_ONCLICK}}/g, stadiumJs);
				                            
				if (i != fifaSchedule.length - 1)
				{
					content += "<div class=\"line-separator\"></div>";
				}
			}
		}
	}

	container.html(content);
}


function showGroupGrid(stage, group){
	
	console.log("Function showGroupGrid()");
		
	var container = $("#grid_container");
	
	if (fifaSchedule != null)
	{
		console.log("fifaSchedule not null and Stage: " + stage + " Group: " + group);
		
		var template = $('#match_table_header_template').text();
	    content = template.replace(/{{TEAM_HEADER}}/g, translate("TEAM_SHORT"))
                          .replace(/{{MATCHS_PLAYED_HEADER}}/g, translate("MATCHS_PLAYED_SHORT"))
                          .replace(/{{WON_HEADER}}/g, translate("WON_SHORT"))
                          .replace(/{{DRAW_HEADER}}/g, translate("DRAW_SHORT"))
                          .replace(/{{LOST_HEADER}}/g, translate("LOST_SHORT"))
                          .replace(/{{POINTS_HEADER}}/g, translate("POINTS_SHORT"));
		
		var matches = getGridTable(stage, group);
		
	    for (var i = 0; i < matches.length; i++) {
		    var item = matches[i];

			var template = $('#match_table_template').text();
		    content = content + template.replace(/{{LOCAL_FLAG}}/g, CssTeamFlags[item.Team])
			                            .replace(/{{TEAM}}/g, item.Team)
			                            .replace(/{{MATCHS_PLAYED}}/g, item.Played)
			                            .replace(/{{WON}}/g, item.Won)
			                            .replace(/{{DRAW}}/g, item.Draw)
			                            .replace(/{{LOST}}/g, item.Lost)
			                            .replace(/{{POINTS}}/g, item.Points);
		}
	}
	

	content = content + "</table><br/>";

	container.html(content);
}

Object.size = function(obj) {
	
	console.log("Function Object.size()");
	
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

// Apply some regular expression to key list to get just keys that match such pattern 
// (let's say /^x/) 
Object.getKeys = function (obj, filter) {
    var name,
        result = [];

    for (name in obj) {
        if ((!filter || filter.test(name)) && obj.hasOwnProperty(name)) {
            result[result.length] = name;
        }
    }
    return result;
};
		
function getGridTable(stage, group) {
	
	console.log("Function getGridTable()");
	
	var matches = new Object();
	
	if (fifaSchedule != null)
	{	
	    for (var i = 0; i < fifaSchedule.length; i++) {
		    var item = fifaSchedule[i];
		
			if (item.Group == group && item.Stage == stage)
			{
				console.log("Local Team: " + item.LocalTeam + " (" + item.LocalGoals + ") - Visitor Team: " + item.VisitorTeam + "(" + item.VisitorGoals + ")" );
				
				// Start IF
				if (item.LocalGoals != null && item.VisitorGoals != null && item.LocalGoals != "" && item.VisitorGoals != "")
				{
					console.log("There are goals");

					var localGoals = parseInt(item.LocalGoals);
					var visitorGoals = parseInt(item.VisitorGoals);
					
					// WON
					if (localGoals > visitorGoals)
					{
						console.log("Local (" + item.LocalTeam + ") > Visitor(" + item.VisitorTeam + ")");
						if (!matches.hasOwnProperty(item.LocalTeam)){
							
							// Local
							matches[item.LocalTeam] = {Played: 1, Won: 1, Draw: 0, Lost:0, Points: Constants.WON_POINTS};
						}
						else
						{
							// Local
							var lResult = matches[item.LocalTeam];
							lResult.Played += 1;
							lResult.Won += 1;
							lResult.Points += Constants.WON_POINTS;
							matches[item.LocalTeam] = lResult;
						}
												
						if (!matches.hasOwnProperty(item.Visitorteam)){
							// Visitor
							matches[item.VisitorTeam] = {Played: 1, Won: 0, Draw: 0, Lost:1, Points: 0};
						}
						else
						{
							// Visitor
							var vResult = matches[item.VisitorTeam];
							vResult.Played += 1;
							vResult.Lost += 1;
							matches[item.VisitorTeam] = vResult;
						}
					}
					if (localGoals < visitorGoals)
					{
						
						console.log("Local (" + item.LocalTeam + ") < Visitor(" + item.VisitorTeam + ")");
						if (!matches.hasOwnProperty(item.LocalTeam)){
							
							// Local
							matches[item.LocalTeam] = {Played: 1, Won: 0, Draw: 0, Lost:0, Points: 0};
						}
						else
						{
							// Local
							var lResult = matches[item.LocalTeam];
							lResult.Played += 1;
							lResult.Lost += 1;
							matches[item.LocalTeam] = lResult;	
						}
						
						if (!matches.hasOwnProperty(item.VisitorTeam)){
							// Visitor
							matches[item.VisitorTeam] = {Played: 1, Won: 1, Draw: 0, Lost:1, Points: Constants.WON_POINTS};
						}
						else
						{						
							// Visitor
							var vResult = matches[item.VisitorTeam];
							vResult.Played += 1;
							vResult.Won += 1;
							vResult.Points += Constants.WON_POINTS;
							matches[item.VisitorTeam] = vResult;
						}
					}
					if (localGoals == visitorGoals)
					{
						console.log("Local (" + item.LocalTeam + ") == Visitor(" + item.VisitorTeam + ")");
						
						if (!matches.hasOwnProperty(item.LocalTeam)){
							
							// Local
							matches[item.LocalTeam] = {Played: 1, Won: 0, Draw: 1, Lost:0, Points: Constants.DRAW_POINTS};
						}
						else
						{
							// Local
							var lResult = matches[item.LocalTeam];
							lResult.Played += 1;
							lResult.Draw += 1;
							lResult.Points += Constants.DRAW_POINTS;
							matches[item.LocalTeam] = lResult;

						}

						if (!matches.hasOwnProperty(item.VisitorTeam)){	
													
							// Visitor
							matches[item.VisitorTeam] = {Played: 1, Won: 0, Draw: 1, Lost:0, Points: Constants.DRAW_POINTS};
						}
						else
						{						
							// Visitor
							var vResult = matches[item.VisitorTeam];
							vResult.Played += 1;
							vResult.Draw += 1;
							vResult.Points += Constants.DRAW_POINTS;
							matches[item.VisitorTeam] = vResult;
						}
					}
				}
				// End IF
				else{

					console.log("There is no match score");
					
					if (!matches.hasOwnProperty(item.LocalTeam)){
						console.log("Adding an element to Local Team: " + item.LocalTeam);

						// Local
						matches[item.LocalTeam] = {Played: 0, Won: 0, Draw: 0, Lost:0, Points: 0};
						
					}
					
					if (!matches.hasOwnProperty(item.VisitorTeam)){
						console.log("Adding an element to Visitor Team: " + item.VisitorTeam);

						// Visitor
						matches[item.VisitorTeam] = {Played: 0, Won: 0, Draw: 0, Lost:0, Points: 0};
					}
				}
			}
		}
	}
	
	// Sort the hash and build an array
	var array = [];
	var matchSize = Object.size(matches);
	var matchKeys = Object.getKeys(matches);
	
    for (var i = 0; i < matchSize; i++) {
    	
    	var team = matchKeys[i];
	    var item = matches[team];
	    item.Team = team;
	    
	    array.push(item);
	}
	
	return array.sort(function(a,b){
		return b.Points - a.Points;
	});

}

function openStadiumPopup(stadiumID)
{
	console.log("Function openStadiumPopup()");

    $( "#fixture_stadium_popup" ).popup();
    $( "#fixture_stadium_popup" ).popup("open");
       
	var container = $("#stadium_container");
	var content = "";      
          
    for (var i = 0; i < fifaSchedule.length; i++) {
	    var item = fifaSchedule[i];
	
		if (item.StadiumID == stadiumID)
		{
			var template = $('#stadium_template').text();
		    content = content + template.replace(/{{NAME}}/g, translate("NAME"))
			                            .replace(/{{STADIUM_NAME}}/g, item.StadiumName)
			                            .replace(/{{CITY}}/g, translate("CITY"))
			                            .replace(/{{STADIUM_CITY}}/g, item.StadiumCity)
			                            .replace(/{{CAPACITY}}/g, translate("CAPACITY"))
			                            .replace(/{{STADIUM_CAPACITY}}/g, item.StadiumCapacity)
			                            .replace(/{{BUILDING_YEAR}}/g, translate("BUILDING_YEAR"))
			                            .replace(/{{STADIUM_YEAR}}/g, item.StadiumYear)
			                            .replace(/{{STADIUM_IMG}}/g, StadiumsImg[item.StadiumCode]);	
			                            		
			container.html(content);
			
			break;
		}
	}

	$("#fixture_stadium_close").click(function() {
		
		$("#fixture_stadium_popup").popup("close");
	});

}

function appendOption(select, option, value, selected)
{
	console.log("Function appendOption()");
		
	if (selected == null) {
		selected=false; 
	} 
	
    select.append(
        $('<option/>', {
            selected: selected,
            value: value,
            text: option
        })
    );
}

function getWindowSizes() {

	console.log("Function getWindowSizes()");
    
	var windowHeight = 0, windowWidth = 0;
	if (typeof (window.innerWidth) == 'number') {
		windowHeight = window.innerHeight;
		windowWidth = window.innerWidth;
      
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		windowHeight = document.documentElement.clientHeight;
    	windowWidth = document.documentElement.clientWidth;
      
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
    	windowHeight = document.body.clientHeight;
		windowWidth = document.body.clientWidth;
	}
  
  return [windowWidth, windowHeight];
}


